package com.boang.dao;

import com.boang.po.Page;
import com.boang.po.Student;
import com.boang.util.DBUtil;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/*
  @author: 13813
  @date: 2024/7/17 9:27
*/
public class StuDaoImpl implements StuDao {
    @Override
    public Page<Student> selectStuList(int pageNum, int pageSize) {
        try {
            Connection conn = DBUtil.getConn();
            PreparedStatement preparedStatement = conn.prepareStatement("select id,name from student order by id desc limit ?,?");
            preparedStatement.setInt(1, (pageNum - 1) * pageSize);
            preparedStatement.setInt(2, pageSize);
            ResultSet resultSet = preparedStatement.executeQuery();
            ArrayList<Student> list = new ArrayList<>();
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                Student student = new Student(id, name);
                list.add(student);
            }

            //总记录数
            PreparedStatement preparedStatement1 = conn.prepareStatement("select count(*) from student");
            ResultSet resultSet1 = preparedStatement1.executeQuery();
            int total = 0;
            while (resultSet1.next()) {
                total = resultSet1.getInt(1);
            }

            int pages = 0;
            if (total % pageSize == 0) {
                pages = total / pageSize;
            } else {
                pages = total / pageSize + 1;
            }
            return new Page<Student>(pageNum, pageSize, pages, total, list);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
